package com.quectel.util.common;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.quectel.util.ex.common.ImageGenException;
import com.quectel.util.ex.common.OperateFileException;
import com.quectel.util.security.UUIDUtils;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.Base64;

public class ImageUtils {
    public static String base64Encode(ByteArrayOutputStream out) {
        try (ByteArrayOutputStream baos = out) {
            return "data:image/jpg;base64," + Base64.getEncoder().encodeToString(baos.toByteArray());
        } catch (IOException e) {
            throw new ImageGenException("Encode image throw exception", e);
        }
    }

    /**
     * url转为可显示的base64
     *
     * @param url
     * @return
     */
    public static String urlToBase64Img(String url) {
        File tempFile = MyFileUtils.downloadToTempDir(url, false);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (BufferedInputStream bis = FileUtil.getInputStream(tempFile)) {
            IoUtil.copy(bis, baos);

        } catch (IOException e) {
            throw new ImageGenException("Image web url convert base64 strings failed", e);
        } finally {
            FileUtil.del(tempFile);
        }
        return base64Encode(baos);
    }

    /**
     * base64转为临时文件
     *
     * @param base64ImgStr
     * @return 使用完成的文件建议删除
     */
    public static File base64ImgToTempFile(String base64ImgStr) {
        if (base64ImgStr != null && base64ImgStr.contains(",")) {
            base64ImgStr = base64ImgStr.substring(base64ImgStr.indexOf(",") + 1);
        }
        if (base64ImgStr != null) {
            byte[] decode = Base64.getDecoder().decode(base64ImgStr);
            File tempFile = new File(FileUtil.getTmpDir(), UUIDUtils.gen32UUID() + ".jpg");
            try (ByteArrayInputStream bais = new ByteArrayInputStream(decode);
                 FileOutputStream fos = new FileOutputStream(tempFile)
            ) {
                IOUtils.copyLarge(bais, fos);
                return tempFile;
            } catch (IOException e) {
                throw new ImageGenException("Base64 image convert temp file failed", e);
            }
        }
        return null;
    }

    /**
     * 压缩图片并保存到临时目录
     *
     * @param srcFile        文件
     * @param keepOriginName 是否保持原文件名 建议不保持防止重复
     * @return 使用完建议删除
     */
    public static File compressImgWriteToTempDir(File srcFile, boolean keepOriginName) {
        long kbSize = srcFile.length() / 1024;
        if (kbSize < 128) {
            //小于128k不压缩
            return srcFile;
        }
        //文件名前半部分
        String prefix = FileUtil.getPrefix(srcFile);
        //文件后半部分
        String suffix = FileUtil.getSuffix(srcFile);
        File destFile = new File(FileUtil.getTmpDir(), prefix + "_bak." + suffix);
        if (kbSize >= 128 && kbSize < 1024) {
            //大于这个区间压缩0.8
            try {
                Thumbnails.of(srcFile).scale(0.5f).toFile(destFile);
            } catch (IOException e) {
                throw new OperateFileException("Compress image file failed", e);
            }
        } else {
            //大于等于1M
            try {
                Thumbnails.of(srcFile).scale(0.2f).toFile(destFile);
            } catch (IOException e) {
                throw new OperateFileException("Compress image file failed", e);
            }
        }
        FileUtil.del(srcFile);
        return destFile;
    }

    /**
     * 压缩图片并保存到临时目录
     *
     * @param in             流对象
     * @param fileName       文件名
     * @param keepOriginName 是否保持原文件名 建议不保持防止重复
     * @return 使用完建议删除
     */
    public static File compressImgWriteToTempDir(InputStream in, String fileName, boolean keepOriginName) {
        File srcFile = MyFileUtils.writeFileToTempDir(in, fileName, keepOriginName);
        return compressImgWriteToTempDir(srcFile, keepOriginName);
    }
}
